package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.support.annotation.NonNull;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.MissionStatisticsDetailListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.MissionDateInfo;
import com.wuliupai.delivery.wuliupaidelivery.bean.MissionStatisticsBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.NumberUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Descriptions：
 * <p>
 * Author：ChenME
 * Date：2017/2/10
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_mission_statistics_detail)
public class MissionStatisticsDetailActivity extends AppBaseActivity {

    @ViewById(R.id.btn_pre)
    Button btn_pre;//pre
    @ViewById(R.id.btn_next)
    Button btn_next;//next

    @ViewById(R.id.tv_currentTime)
    TextView tv_currentTime;

    @ViewById(R.id.tv_fistItemLabel)
    TextView tv_fistItemLabel;
    @ViewById(R.id.tv_fistItemValue)
    TextView tv_fistItemValue;

    @ViewById(R.id.tv_secondItemLabel)
    TextView tv_secondItemLabel;
    @ViewById(R.id.tv_secondItemValue)
    TextView tv_secondItemValue;

    @ViewById(R.id.tv_thirdItemLabel)
    TextView tv_thirdItemLabel;
    @ViewById(R.id.tv_thirdItemValue)
    TextView tv_thirdItemValue;

    @ViewById(R.id.listView)
    ListView listView;

    private final String[] MenuNames = {"切换为年", "切换为月"};

    private MenuItem menuItem;

    private boolean isYear = false;
    private int monthInterval = 0;
    private int yearInterval = 0;
    private List<MissionDateInfo> dataListMonth;
    private List<MissionDateInfo> dataListYear;
    private MissionStatisticsDetailListAdapter mAdapter;

    SimpleDateFormat mFormatterMonth = new SimpleDateFormat("yyyy-MM");
    SimpleDateFormat mFormatterYear = new SimpleDateFormat("yyyy");


    @AfterViews
    void onPageStart() {
        setTitle(this, R.string.string_missionStatisticsDetail_title, R.drawable.comm_press_return_selector,
                true, new OnNavigationBtnClickListener() {
                    @Override
                    public void navigationClick() {
                        onBackPressed();
                    }

                    @Override
                    public void menuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menuItem1:
                                isYear = !isYear;
                                menuItem.setTitle(MenuNames[isYear ? 1 : 0]);
                                setTime();
                                setBtn();
                                refreshData();
                                break;
                        }
                    }
                });
        init();
    }

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menuItem = menu.findItem(R.id.menuItem1);
        menuItem.setVisible(true);
        menuItem.setTitle(MenuNames[0]);
        menu.findItem(R.id.menuItem2).setVisible(false);
        return true;
    }

    private void init() {
        setTime();
        setBtn();

        dataListMonth = new ArrayList<>();
        dataListYear = new ArrayList<>();
        mAdapter = new MissionStatisticsDetailListAdapter(this);
        listView.setAdapter(mAdapter);
        refreshData();
    }

    /**
     * 设置按钮文案
     */
    private void setBtn() {
        if (isYear) {
            btn_pre.setText(getString(R.string.string_missionStatisticsDetail_yearPreBtn));
            btn_next.setText(getString(R.string.string_missionStatisticsDetail_yearNextBtn));
        } else {
            btn_pre.setText(getString(R.string.string_missionStatisticsDetail_monthPreBtn));
            btn_next.setText(getString(R.string.string_missionStatisticsDetail_monthNextBtn));
        }
    }

    /**
     * 刷新数据源
     */
    private void refreshData() {

        if ((isYear && dataListYear.size() <= 0) || (!isYear && dataListMonth.size() <= 0)) {
            loadData();
            return;
        }
        setViewDate();
        mAdapter.setBaseKPI(isYear ? baseKPIYear : baseKPIMonth);
        mAdapter.setData(isYear ? dataListYear : dataListMonth);
        mAdapter.setPage(isYear ? MissionStatisticsBean.Type_Year : MissionStatisticsBean.Type_Month);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 加载数据
     */
    private void loadData() {
        String url = "";
        MissionStatisticsBean requestBean = new MissionStatisticsBean();

        if (isYear) {
            url = InterfaceNet.Net_GetMissionStatisticsByYear;
            requestBean.setYear(mFormatterYear.format(getCalendar().getTime()));
        } else {
            url = InterfaceNet.Net_GetMissionStatisticsByMonth;
            requestBean.setDate(mFormatterMonth.format(getCalendar().getTime()));
        }
        String requestJson = JsonUtils.createJsonString(requestBean);
        LogUtils.log("请求数据~~~" + requestJson);
        String requestAes = null;
        try {
            requestAes = JsonUtils.aes(requestJson);
            callNet(this, url, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    Object obj = JsonUtils.parseJsonString(content, MissionStatisticsBean.class);
                    if (obj instanceof MissionStatisticsBean) {
                        MissionStatisticsBean bean = (MissionStatisticsBean) obj;
                        if (null != bean) {
                            if (isYear) {
                                baseKPIYear = bean.getStandardKPI();
                                currentKPIYear = bean.getActualKPI();
                                dataListYear = bean.getInfolist();
                            } else {
                                dataListMonth = bean.getInfolist();
                                baseKPIMonth = bean.getStandardKPI();
                                currentKPIMonth = bean.getActualKPI();
                            }
                            refreshData();
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                    App.toast("暂无数据！");
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setViewDate() {
        int baseKPI = isYear ? baseKPIYear : baseKPIMonth;
        int currentKPI = isYear ? currentKPIYear : currentKPIMonth;
        tv_fistItemValue.setText((baseKPI / 100) + "");
        tv_secondItemValue.setText((currentKPI / 100) + "");
        tv_thirdItemValue.setText(StringUtils.dropNeedlessZeroOfNum(
                NumberUtils.formatDouble(((currentKPI * 1f) / (baseKPI * 1f)) * 100, "0.00") + "") + "%");
    }

    int baseKPIYear = 0;
    int currentKPIYear = 0;
    int baseKPIMonth = 0;
    int currentKPIMonth = 0;

    private void cleanView() {
        tv_fistItemValue.setText("暂无");
        tv_secondItemValue.setText("暂无");
        tv_thirdItemValue.setText("暂无");
    }

    /**
     * 更新时间
     */
    private void setTime() {
        Calendar calendar = getCalendar();
        String currentDate = calendar.get(Calendar.YEAR) + "年";
        setNextBtnEnable();

        if (!isYear) {
            currentDate += (calendar.get(Calendar.MONTH) + 1) + "月";
        }
        tv_currentTime.setText(currentDate);
    }

    /**
     * 设置下一个月/年的enable
     */
    private void setNextBtnEnable() {
        boolean enable = (isYear && yearInterval < 0) || (!isYear && monthInterval < 0);
        btn_next.setEnabled(enable);
        if (enable) {
            btn_next.setTextColor(getResources().getColor(R.color.color_defaultText));
        } else {
            btn_next.setTextColor(getResources().getColor(R.color.color_defaultTextLighter));
        }
    }

    /**
     * 获取日期
     *
     * @return
     */
    @NonNull
    private Calendar getCalendar() {
        Calendar calendar = Calendar.getInstance();
        if (isYear) {
            calendar.add(Calendar.YEAR, yearInterval);
        } else {
            calendar.add(Calendar.MONTH, monthInterval);
        }
        return calendar;
    }

    /**
     * 上一个月/年
     */
    @Click(R.id.btn_pre)
    void onPreBntClick() {
        if (isYear) {
            yearInterval--;
            dataListYear.clear();
        } else {
            monthInterval--;
            dataListMonth.clear();
        }
        setTime();
        cleanView();
        refreshData();
    }

    /**
     * 下一个月/年
     */
    @Click(R.id.btn_next)
    void onNextBtnClick() {
        if (isYear) {
            yearInterval++;
            dataListYear.clear();
        } else {
            monthInterval++;
            dataListMonth.clear();
        }
        setNextBtnEnable();
        setTime();
        cleanView();
        refreshData();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }
}